﻿using DAL.Engine.Domain;
using NH = DAL.Nhibernate.Interface;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHC = NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;
using System;
using System.Reflection;

namespace DAL.Nhibernate.Configuration
{
    public class NHibernateInMemoryConfigurationManager : NH.IConfigurationManager
    {
        public ISession GetSession()
        {
            return SessionFactory.OpenSession();
        }

        public static ISessionFactory SessionFactory = GetSessionFactory();
        private static NHC.Configuration SavedConfig { get; set; }

        private static ISessionFactory GetSessionFactory()
        {
            return Fluently.Configure()
                    .Database(SQLiteConfiguration.Standard.InMemory().ShowSql())
                    .Mappings(BuildMap)
                    .ExposeConfiguration(BuildSchema)
                    .BuildSessionFactory();
        }

        private static void BuildMap(MappingConfiguration map)
        {
            map.FluentMappings.AddFromAssemblyOf<User>();
            map.HbmMappings.AddFromAssembly(Assembly.GetExecutingAssembly());
        }

        private static void BuildSchema(NHC.Configuration cfg)
        {
            new SchemaExport(cfg).Create(false, true);
        }

    }
}
